const express = require('express')
const querystring = require('querystring')
const app = express()

app.use((req, res, next) => {
    let dataStr = ''
    let timestamp = '';

    req.on('data', chunk => {
        dataStr += chunk
        timestamp = Date.parse(new Date())
    })

    req.on('end', () => {
        console.log(dataStr)
        console.log(timestamp)
        const obj = querystring.parse(dataStr)
        // 把 username=ls&password=123 字符串，解析为 { username: 'ls', password: 123 }
        obj.time = timestamp
        req.body = obj
        next()
    })
})

app.get('/', (req, res) => {
    res.sendFile('./index.html', { root: __dirname })
})

app.post('/postdata', (req, res) => {
    console.log(req.body)
    res.send(req.body)
})

// 调用 app.listen 方法，指定端口号并启动web服务器
app.listen(3001, function() {
    console.log('Express server running at http://127.0.0.1:3001')
})
